package com.kerbores.blog.service.impl;

import org.nutz.dao.Cnd;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Lang;
import org.nutz.lang.Strings;
import org.nutz.lang.util.NutMap;

import com.kerbores.blog.bean.User;
import com.kerbores.blog.bean.User.Level;
import com.kerbores.blog.constant.Constant;
import com.kerbores.blog.dao.IUserDao;
import com.kerbores.blog.service.IUserService;
import com.kerbores.utils.entries.Result;

/**
 * @author 贵源 <br>
 *         create at 2014年10月19日
 */
@IocBean(name = "userService")
public class UserServiceImpl implements IUserService {

	@Inject
	private IUserDao userDao;

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.kerbores.blog.service.IUserService#login(java.lang.String,
	 * java.lang.String)
	 */
	@Override
	public Result login(String userName, String password) {
		User check = userDao.findByCondition(Cnd.where("email", "=", userName));
		if (check == null) {
			return Result.fail("用户不存在");
		}
		if (!Strings.equals(Lang.md5(password), check.getPassword())) {
			return Result.fail("密码不正确");
		}
		NutMap data = new NutMap();
		data.put(Constant.LOGIN_USER_SESSION_KEY, check);
		return Result.success(data);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.kerbores.blog.service.IUserService#get(int)
	 */
	@Override
	public User get(int i) {
		throw Lang.noImplement();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.kerbores.blog.service.IUserService#adminLogin(java.lang.String,
	 * java.lang.String)
	 */
	@Override
	public Result adminLogin(String userName, String password) {
		User check = userDao.findByCondition(Cnd.where("userName", "=", userName));
		if (check == null) {
			return Result.fail("用户不存在");
		}
		if (!Strings.equals(Lang.md5(password), check.getPassword())) {
			return Result.fail("密码不正确");
		}
		if (check.getLevel() != Level.ADMIN) {
			return Result.fail("没有权限");
		}
		NutMap data = new NutMap();
		data.put(Constant.LOGIN_USER_SESSION_KEY, check);
		return Result.success(data);
	}
}
